package com.cn.mmd.controller;

import com.cn.mmd.mapper.EmploymentQuestMapper;
import com.cn.mmd.model.*;
import com.cn.mmd.service.*;
import com.cn.mmd.tools.AliyunOssUtil;
import com.cn.mmd.tools.PictureUtil;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.*;


/**
 * 就业问卷
 * Created by Administrator on 2016/7/8.
 */

    @Controller
    @RequestMapping(value = "EmploymentQuestionnaire")
    public class EmploymentQuestionnaireController {

    @Autowired
    EmploymentService employmentService;
    @Autowired
    TeacherService teacherService;
    @Autowired
    StudentService studentService;
    @Autowired
    QuestionnaireService questionnaireService;
    @Autowired
    TokenController tokenController;


    /**
     *发布就业问卷
     * @param request
     * @return
     */
    @RequestMapping(value = "publishEmployment")
    public synchronized
    @ResponseBody
    Map<String, Object> publishEmployment(HttpServletRequest request) {
        Map<String, Object> map = new HashMap<String, Object>();

        String publishObjects = "班级";//默认就业问卷面向群体为班级

        String publisherId = request.getParameter("publisherId");//发布方id
        String releaseToWho=request.getParameter("releaseToWho");//问卷具体面向的对象，如具体的班级、课程等

        String questionnaireTitle = request.getParameter("questionnaireTitle");//问卷标题
        String questionnaireExplain=request.getParameter("questionnaireExplain");//问卷说明  该问卷的作用标记，暂时有教评、SCL-90、就业和“”
        Date now = new Date();
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");//可以方便地修改日期格式
        String nowTime = dateFormat.format( now );//时间

        String questionnaireURL=request.getParameter("questionnaireURL");//就业问卷链接

        Questionnaire questionnaire1=new Questionnaire(publisherId,publishObjects,questionnaireTitle,nowTime,questionnaireExplain,releaseToWho);

        int a=questionnaireService.insertQuestionnaire(questionnaire1);//添加问卷

        if (a>0) {//添加成功
            Questionnaire questionnaire2 = questionnaireService.selectPrimaryKey(publisherId, publishObjects, questionnaireTitle, nowTime);//查出当前问卷的id

            int questionnaireId = questionnaire2.getQuestionnaireid();//问卷id

            int number = 0;

            String[] releaseToWho1 = questionnaire2.getReleasetowho().split(",");//班级可能有多个，用逗号分割

            List cList = new ArrayList();
            for (int i = 0; i < releaseToWho1.length; i++) {
               System.out.println("releaseToWho1[i]: " + releaseToWho1[i]);
                int num = questionnaireService.selectNumber(releaseToWho1[i]);
                System.out.println("人数："+num);
                number += num;//统计人数
                List studentIdList = questionnaireService.selectByStudentClass(releaseToWho1[i]);
                System.out.print("studentIdList: " + studentIdList.size());
                if (studentIdList.size() > 0) {
                    for (int n = 0; n < studentIdList.size(); n++) {

                        System.out.print("   studentId" + studentIdList.get(n));
                        String state = "NO";//设置状态为未填写

                        QuestionnaireStudent questionnaireStudent = new QuestionnaireStudent((String) studentIdList.get(n), questionnaireId, state, nowTime);

                        int c = studentService.insertStuQues(questionnaireStudent);
                        System.out.println("是否添加成功？："+c);
                        cList.add(c);
                    }
                } else {
                        System.out.println("未查到相关学生");
                }
            }
          //  System.out.print("number:" + number + "---cList:" + cList.size());
            if (cList.size() != number) {
                map.put("code", 201);
                map.put("message", "问卷关联学生失败");
//                map.put("data", "");
                return map;
            }
            QuestionnaireStatistical questionnaireStatistical=new QuestionnaireStatistical();

            questionnaireStatistical.setQuestionnaireid(questionnaireId);
            questionnaireStatistical.setPublishobjects(releaseToWho);
            questionnaireStatistical.setNumber(number);
            questionnaireStatistical.setNotchoosenumber(number);
            questionnaireStatistical.setChoosenumber(0);
            int c=questionnaireService.insertStatistical(questionnaireStatistical);
            if (c>0){
                System.out.println("统计人数成功");
            }else{
                map.put("code",201);
                map.put("message","人数统计失败");
//                map.put("data", "");
                return map;
            }

            EmploymentQuestionnaire employmentQuestionnaire=new EmploymentQuestionnaire(questionnaireId,questionnaireURL);

            int b=employmentService.insertEmploymentQuestionnaire(employmentQuestionnaire);
            if (b<=0) {
                map.put("code", 202);
                map.put("message", "添加就业问卷链接失败");
//                map.put("data", "");
                return map;
            }
            System.out.println("成功");
            map.put("code", 200);
            map.put("message", "发布就业问卷成功");
//            map.put("data", "");
        }else {
            map.put("code", 203);
            map.put("message", "发布问卷失败");
//            map.put("data", "");
            return map;
        }
        return map;
    }



        /**
         *设置就业问卷
         * @param request
         * @return
         */
        @RequestMapping(value = "EmploymentQuest")
        public synchronized
        @ResponseBody
        Map<String, Object> EmploymentQuest(HttpServletRequest request) {
            Map<String, Object> map = new HashMap<String, Object>();

            String employment=request.getParameter("employment");//问卷信息

            JSONArray jsonArray=JSONArray.fromObject(employment);

            EmploymentQuest employmentQuest=null;
            List list=new ArrayList();
            for (int i=0;i<jsonArray.size();i++){

                JSONObject jsonObject=jsonArray.getJSONObject(i);
                int questionNum=jsonObject.getInt("questionNum");//问题序号
                String questionContent=jsonObject.getString("questionContent");//问题内容
                String questionnaireName=jsonObject.getString("questionnaireName");//问卷名
                String options=jsonObject.getString("options");//选项，填空题为空，选择题为其选项，用！拼接，选项_最大分，用！拼接
                //格式：选择题：选项1！选项2！选项3。。。 打分题：选项1_5！选项2_5！选项3_5。。。
                String problemTypes=jsonObject.getString("problemTypes");//问题类型，选择题、打分题、填空题
                String questionEffect=jsonObject.getString("questionEffect");//该问题统计的作用（头）

                employmentQuest=new EmploymentQuest();
                employmentQuest.setQuestionnum(questionNum);
                employmentQuest.setQuestioncontent(questionContent);
                employmentQuest.setQuestionnairename(questionnaireName);
                employmentQuest.setOptions(options);
                employmentQuest.setProblemtypes(problemTypes);
                employmentQuest.setQuestioneffect(questionEffect);

                int b=employmentService.insertEmploymentQuest(employmentQuest);

                if (b>0){
                    list.add(b);
                }
            }
            if (list.size()==jsonArray.size()){
                //成功
                map.put("code",200);
                map.put("message","设置问卷成功");
                map.put("data", jsonArray);
            }else {
                map.put("code",201);
                map.put("message","设置问卷失败");
//                map.put("data","");
            }

            return map;
        }

        /**
         *通过时间查询就业问卷统计结果
         * @param request
         * @return
         */
        @RequestMapping(value = "selectEmploymentStatistical")
        public synchronized
        @ResponseBody
        Map<String, Object> selectEmploymentStatistical(HttpServletRequest request) {
            Map<String, Object> map = new HashMap<String, Object>();
            Map<String, Object> map1 = new HashMap<String, Object>();

           // SELECT * from 你要查的表名 where 自增长的主键/日期=(select max(主键/日期) from 你要查的表名);

            String startTime=request.getParameter("startTime");//开始时间
            String entTime=request.getParameter("entTime");//结束时间

            map1.put("startTime",startTime);
            map1.put("entTime",entTime);

            List<EmploymentQuestStatistical> list=employmentService.selectNewStatisical(map1);

            if (list!=null){
           //     System.out.println("成功");
                map.put("code",200);
                map.put("message","查询就业问卷统计成功");
                map.put("data",list);
            }else {
            //    System.out.println("失败");
                map.put("code",201);
                map.put("message","查询就业问卷统计失败");
//                map.put("data","");
            }

            return map;
        }

        /**
         *添加就业问卷统计
         * @param request
         * @return
         */
        @RequestMapping(value = "insertEmploymentStatistical")
        public synchronized
        @ResponseBody
        void insertEmploymentStatistical(MultipartHttpServletRequest request) throws Exception{
            //,@RequestParam(value = "file", required = false)MultipartFile file
            Map<String, Object> map = new HashMap<String, Object>();
            List<Map> maplist=new ArrayList<Map>();

            System.out.println("进入添加就业问卷统计接口！！");
            Date now = new Date();
            SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");//可以方便地修改日期格式
            String nowTime = dateFormat.format( now );//时间
            String questionnaireTitle=request.getParameter("questionnaireTitle");//问卷标题
            String questionnaireURL=request.getParameter("questionnaireURL");//URL
            System.out.println("问卷标题！！"+questionnaireTitle);
//            String optionStatistical=jsonObject.getString("optionStatistical");//选项的统计结果  格式：选项1_统计！选项2_统计。。
//            //填空题为空，选择题为其选项，用！拼接，打分题为：选项_得分，用！拼接
//            //格式：选择题：选项1_统计结果！选项2_统计结果！选项3_统计结果。。。 打分题：选项1_得分！选项2_得分！选项3_得分。。。

            String []questionIds=request.getParameterValues("questionNum");
        //    System.out.print("---问题序号：" + questionIds.length);
//            for (int a=0;a<questionIds.length;a++){
//                String questionNum=questionIds[a];
          //      System.out.print("---问题序号：" + questionNum);
//            }

            String[] questionStates=request.getParameterValues("questionState");
            String[] questionDescribes=request.getParameterValues("questionDescribe");
         //   System.out.println("该问题统计的作用："+questionEffects.length);

            List<String> list=new ArrayList<String>();
            List<MultipartFile> file = request.getFiles("statisticalPhoto");
            String path = request.getSession().getServletContext().getRealPath("/") + "upload"; // 获取本地存储路径
//            System.out.println(path + "-----------------");
//            System.out.println(file.size()+"=====================");
            String statisticalPhotoURL = "";
            for (int i = 0; i < file.size(); i++) {
                if (!file.get(i).isEmpty()) {
//                    String path=request.getSession().getServletContext().getRealPath("/") + "upload";
                    File targetFile;
                    String key =nowTime +"number"+questionIds[i]+file.get(i).getOriginalFilename();
                    targetFile = new File(path,key);
                    if (!targetFile.exists()) {
                        targetFile.mkdirs();
                        try {
                            file.get(i).transferTo(targetFile);
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    } else {
                        targetFile.delete();
                        try {
                            file.get(i).transferTo(targetFile);
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    }
                    PictureUtil pictureUtil = new PictureUtil();
                    pictureUtil.zipWidthHeightImageFile(targetFile.getPath(),800,300,4);
                    statisticalPhotoURL = AliyunOssUtil.save(key, targetFile.getPath());

                    list.add(statisticalPhotoURL);

                    targetFile.delete();
                }else {
                    list.add("");
                }
            }

            String [] optionStatisticals=request.getParameterValues("optionStatistical");
          //  System.out.println("选项的统计结果："+optionStatisticals.length);

            String[] numberOfPeoples=request.getParameterValues("numberOfPeople");
           // System.out.println("该题统计的总人数："+numberOfPeoples.length);
            int[] intTemp = new int[numberOfPeoples.length];
            for (int i = 0; i <numberOfPeoples.length; i++)
                {
                intTemp[i] = Integer.parseInt(numberOfPeoples[i]);
                }

            List<Integer> list1=new ArrayList<Integer>();
           // System.out.println("new对象");
            EmploymentQuestStatistical employmentQuestStatistical=null;
            //EmploymentQuest employmentQuest=null;
          //  System.out.println("new对象完成");
            for (int i=0;i<questionIds.length;i++){
                int questionNum=Integer.parseInt(questionIds[i]);

                int numberOfPeople=Integer.parseInt(numberOfPeoples[i]);
                String optionStatistical=optionStatisticals[i];
                String questionState=questionStates[i];
                String questionDescribe=questionDescribes[i];
                String url=list.get(i);

//                questionnaireTitle=request.getParameter("questionnaireTitle");//问卷标题
//                String questionnaireURL
                employmentQuestStatistical=new EmploymentQuestStatistical();
                employmentQuestStatistical.setQuestionnairetitle(questionnaireTitle);
                employmentQuestStatistical.setQuestionnaireurl(questionnaireURL);
                employmentQuestStatistical.setQuestionnum(questionNum);
                employmentQuestStatistical.setOptionstatistical(optionStatistical);
                employmentQuestStatistical.setQuestionstate(questionState);
                employmentQuestStatistical.setQuestiondescribe(questionDescribe);
                employmentQuestStatistical.setNumberofpeople(numberOfPeople);
                employmentQuestStatistical.setStatisticalphoto(url);
                employmentQuestStatistical.setStatisticaltime(nowTime);

                int b=employmentService.insertEmploymentQuestStatistical(employmentQuestStatistical);

                Map<String, Object> map1 = new HashMap<String, Object>();
                map1.put("questionNum",questionNum);
                map1.put("questionnaireTitle",questionnaireTitle);
                map1.put("questionnaireURL",questionnaireURL);
                map1.put("optionStatistical",optionStatistical);
                map1.put("questionState",questionState);
                map1.put("questionDescribe",questionDescribe);
                map1.put("numberOfPeople",numberOfPeople);
                map1.put("url",url);
                map1.put("nowTime",nowTime);

                maplist.add(map1);
                if (b>0){
                    //成功
                    list1.add(b);
                }
            }
            if (list1.size()==questionIds.length){
                map.put("message","添加统计成功");
                map.put("code",200);
//                map.put("data","");
                System.out.println("就业问卷统计成功");
            }else {
                map.put("message","添加统计失败");
                map.put("code",201);
//                map.put("data","");
                System.out.println("就业问卷统计失败");
            }

        }


    /**
     *修改学生问卷关联状态(就业问卷  其他问卷不需要)
     * @param request
     * @return
     */
    @RequestMapping(value = "updateEmploymentState")
    public synchronized
    @ResponseBody
    Map<String, Object> updateEmploymentState(HttpServletRequest request) throws Exception {
        //,@RequestParam(value = "file", required = false)MultipartFile file
        Map<String, Object> map = new HashMap<String, Object>();

        String studentId=request.getParameter("studentId");//学生id
        int questionnaireId=Integer.parseInt(request.getParameter("questionnaireId"));//问卷id

        String token=request.getParameter("token");

        StudentApp studentApp;
        studentApp = (StudentApp) tokenController.token1(studentId, token);
        if (studentApp==null){
            map.put("code", 203);
            map.put("message", "您暂无权限做此操作");
//            map.put("data", "");
            return map;
        }

        String state="YES";//设置状态为YES

        QuestionnaireStudent questionnaireStudent=new QuestionnaireStudent();

        questionnaireStudent.setStudentid(studentId);
        questionnaireStudent.setQuestionnaireid(questionnaireId);
        questionnaireStudent.setState(state);

        int x=studentService.updateState(questionnaireStudent);
        if (x>0){
            //状态修改成功
            map.put("code",200);
            map.put("message","修改学生问卷关联状态成功");
//            map.put("data","");
        }else {
            map.put("code",201);
            map.put("message","修改学生问卷关联状态失败");
//            map.put("data","");
            return map;
        }

        return map;
    }
}

